package Classing;
/**
 *二叉搜索树
 */
public class BinarySearchTree {
    static class TreeNode {
        public int val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }
    }

    public TreeNode root ;

    public boolean search(int val) {
        //找到val
        TreeNode cur = root;
        while(cur != null) {
            if(val > cur.val) {
                cur = cur.right;
            } else if(val < cur.val) {
                cur = cur.left;
            } else {
                return true;
            }
        }
        return false;
    }

    public void insert(int val) {
        TreeNode cur = root;
        TreeNode parent = cur;
        //第一个结点
        if(root == null) {
            root = new TreeNode(val);
            return;
        }
        while(cur != null) {
            parent = cur;
            if(val > cur.val) {
                cur = cur.right;
            } else if(val < cur.val) {
                cur = cur.left;
            } else {
                return;
            }
        }
        if(val > parent.val) {
            parent.right = new TreeNode(val);
        } else {
            parent.left = new TreeNode(val);
        }
    }
}